<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>随机闪烁灯</title>
	</head>
	<body>
		<span>请输入要显示的彩灯数：</span>
		<input type="text" id="in" />
		<button id="bt1">生成</button>
		<button id="bt2">清除</button>
		<hr />
		<div id="div1"></div>
		<script>
		function create(){
			var fragment=document.createDocumentFragment();
			var num=document.getElementById("in").value;
			if(isNaN(num)){
				alert("输入数字不合法");
				return false;
			}else if(num==''){
				alert("输入不能为空！！");
				return false;
			}else{
				for(var i=0;i<num;i++){
					var e=document.createElement("img");
					e.setAttribute("src","../js素材/off.png");
					e.setAttribute("width","150px");
					fragment.appendChild(e);
				}
				document.getElementById("div1").appendChild(fragment);
				
			}
		}
		function light(){
		var arrays=document.getElementsByTagName("img");
			for(var i=0;i<arrays.length;i++){
				if(Math.random()>0.5){
					arrays[i].setAttribute("src","../js素材/on.png");
				}else{
					arrays[i].setAttribute("src","../js素材/off.png");
				}
			}
			setTimeout(light,50);
		}
		setTimeout(light,0);
		function clear(){
			var ele=document.getElementById("div1");
			while(ele.hasChildNodes()){
				ele.removeChild(ele.lastChild);
			}
		}
		document.getElementById("bt1").addEventListener("click",create,true);
		document.getElementById("bt2").addEventListener("click",clear,true);
		</script>
	</body>
</html>
